package site.qjdb.util;

import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


/**
 * MD5工具类
 *
 * */
public class MD5Utils {
	
	private final static int SALT_LENGTH = 6;
	
    // 全局数组
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
            "E", "F" };

    /**
     * 获取加密后的密码，在后面加盐
     */
    public static String md5(String password) {
        String salt = getRandomString(SALT_LENGTH);
        return GetMD5Code(password) + salt;
    }

    /**
     * 比对未加密的密码和加密后的密码是否一致
     */
    public static boolean md5Compare(String password, String encryptPassword) {
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(encryptPassword)) {
            return false;
        }
        return GetMD5Code(password).equals(encryptPassword.substring(0, encryptPassword.length() - SALT_LENGTH));
    }

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    /*
     * 传入字符串，生成MD5加密后的字符串
     */
    private static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }
    
    /**
     * 获取随机字符串
     *
     * @param length
     */
    private static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            s.append(str.charAt(number));
        }
        return s.toString().toUpperCase();
    }
}